package com.xincheng.shuimalong.activity.recept;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.alertview.OnAlertItemClickListener;
import com.xincheng.library.xlog.XLog;
import com.xincheng.library.xswipemenurecyclerview.holder.RecyclerHolder;
import com.xincheng.library.xswipemenurecyclerview.listener.OnItemClickListener;
import com.xincheng.library.xswipemenurecyclerview.swipe.Closeable;
import com.xincheng.library.xswipemenurecyclerview.swipe.Direction;
import com.xincheng.library.xswipemenurecyclerview.swipe.DirectionMode;
import com.xincheng.library.xswipemenurecyclerview.listener.OnSwipeMenuItemClickListener;
import com.xincheng.library.xswipemenurecyclerview.swipe.SwipeMenu;
import com.xincheng.library.xswipemenurecyclerview.swipe.SwipeMenuCreator;
import com.xincheng.library.xswipemenurecyclerview.swipe.SwipeMenuItem;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.activity.config.CitySelectActivity;
import com.xincheng.shuimalong.activity.config.InsuranceCompanyActivity;
import com.xincheng.shuimalong.adapter.recept.AcceptanceAdapter;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.config.CommonConfig;
import com.xincheng.shuimalong.entity.config.District;
import com.xincheng.shuimalong.entity.config.RegionData;
import com.xincheng.shuimalong.entity.recept.Acceptance;
import com.xincheng.shuimalong.recyclerview.CardSwipeMenuRecyclerView;
import com.xincheng.shuimalong.util.ConfigUtil;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.ShowActivity;
import com.xincheng.shuimalong.view.CardItemDecoration;
import com.xincheng.shuimalong.view.picker.AreaPickerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xiaote on 2017/6/20.
 */

public class MyAcceptanceActivity extends BaseActivity {
    @BindView(R.id.receipt_bill_city_tv)
    TextView mAreaTv;
    @BindView(R.id.receipt_bill_insurance_company_tv)
    TextView mCompanyTv;
    @BindView(R.id.receipt_bill_swipemenu_rv)
    CardSwipeMenuRecyclerView mBillRv;

    private List<Acceptance.Data> mBillList;
    private AcceptanceAdapter mAdapter;
    private String mToken;
    private int mCurrentPosition = -1;

    private CommonConfig mCompany;

    private SwipeMenuCreator mMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.item_width);
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            SwipeMenuItem deleteItem = new SwipeMenuItem(MyAcceptanceActivity.this)
                    .setBackgroundDrawable(R.drawable.item_delete_bg)
                    .setText(getString(R.string.delete)) // 文字，还可以设置文字颜色，大小等。。
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(deleteItem);
        }
    };

    @Override
    public int getLayoutResId() {
        return R.layout.activity_issue_receipt_bill;
    }

    @Override
    public void initData() {
        initTitleBarOfRight(getString(R.string.issue_receipt_bill));
        mToken = PrefUtil.getString(this, PrefKey.TOKEN, "");
        mBillRv.setLayoutManager(new LinearLayoutManager(this));
        mBillRv.addItemDecoration(new CardItemDecoration());
        mBillRv.setSwipeMenuCreator(mMenuCreator);
        mAdapter = new AcceptanceAdapter(this);
        mBillRv.setAdapter(mAdapter);
        getMyAcceptance();
    }

    @Override
    public void addListener() {
        mBillRv.setOnSwipeMenuItemClickListener(new MyOnSwipeMenuItemClickListener());
        mBillRv.setOnItemClickListener(new MyOnItemClickListener());
    }

    /**
     * 获取我的收单
     */
    private void getMyAcceptance() {
        RetroSubscrube.getInstance().getSubscrube(GetParam.getMyAcceptance(mToken),
                new BaseObserver(this, getString(R.string.loading_data)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        if (data != null) {
                            Acceptance acceptance = GsonUtil.parseData(data, Acceptance.class);
                            mBillList = acceptance.getAcceptanceList();
                            mAdapter.refreshData(mBillList);
                        }
                    }
                });
    }

    /**
     * 删除我的收单
     */
    private void deleteMyAcceptance() {
        int acId = mAdapter.getItem(mCurrentPosition).getAcId();
        RetroSubscrube.getInstance().getSubscrube(GetParam.delMyAcceptance(mToken, acId),
                new BaseObserver(this, getString(R.string.loading_data)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        CommonUtil.showToast(getContext(), msg);
                        mAdapter.removeData(mCurrentPosition);
                    }
                });
    }

    @OnClick({R.id.receipt_bill_city_layout, R.id.receipt_bill_insurance_company_layout, R.id.common_right_iv})
    public void onClick(View v) {
        Bundle extras = new Bundle();
        switch (v.getId()) {
            case R.id.receipt_bill_city_layout:
//                mAreaPickerView.show();
                extras.putInt(IntentKey.FROM, 1);
                ShowActivity.showActivityForResult(this, CitySelectActivity.class, extras,
                        RequestCodeKey.GO_CITY_SELECT);
                break;
            case R.id.receipt_bill_insurance_company_layout:
                extras.putInt(IntentKey.FROM, 1);
                if (mCompany != null) {
                    extras.putParcelable(IntentKey.INSURANCE_COMPANY, mCompany);
                }
                ShowActivity.showActivityForResult(this, InsuranceCompanyActivity.class, extras,
                        RequestCodeKey.GO_INSURANCE_COMPAY_SELECT);
                break;
            case R.id.common_right_iv:
                ShowActivity.showActivityForResult(this, FillReceiptInfoActivity.class,
                        RequestCodeKey.GO_PUBLISH_ACCEPTANCE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCodeKey.GO_CITY_SELECT:
                    int cityId = 0;
                    if (!CommonUtil.isEmpty(mBillList)) {
                        CommonConfig hotCity = data.getParcelableExtra(IntentKey.HOT_CITY);
                        RegionData province = data.getParcelableExtra(IntentKey.PROVINCE);
                        RegionData city = data.getParcelableExtra(IntentKey.CITY);
                        List<Acceptance.Data> list = new ArrayList<>();
                        if (hotCity != null) {
                            mAreaTv.setText(hotCity.getName());
                            cityId = hotCity.getId();
                            for (int i = 0; i < mBillList.size(); i++) {
                                if (cityId == mBillList.get(i).getCityId()) {
                                    list.add(mBillList.get(i));
                                }
                            }
                        } else if (city != null) {
                            mAreaTv.setText(city.getName());
                            for (int i = 0; i < mBillList.size(); i++) {
                                if (city.getId() == mBillList.get(i).getCityId()) {
                                    list.add(mBillList.get(i));
                                }
                            }
                        } else if (province != null) {
                            mAreaTv.setText(province.getName());
                            for (int i = 0; i < mBillList.size(); i++) {
                                if (province.getId() == mBillList.get(i).getProvinceId()) {
                                    list.add(mBillList.get(i));
                                }
                            }
                        }
                        mAdapter.refreshData(list);
                    }
                    break;
                case RequestCodeKey.GO_INSURANCE_COMPAY_SELECT:
                    mCompany = data.getParcelableExtra(IntentKey.INSURANCE_COMPANY);
                    if (mCompany == null) {
                        return;
                    }
                    if (mCompany.getId() == 0) {
                        mCompanyTv.setText(getString(R.string.insurance_company));
                        mAdapter.refreshData(mBillList);
                        return;
                    }
                    mCompanyTv.setText(mCompany.getName());
                    if (!CommonUtil.isEmpty(mBillList)) {
                        List<Acceptance.Data> list = new ArrayList<>();
                        for (int i = 0; i < mBillList.size(); i++) {
                            if (mCompany.getId() == mBillList.get(i).getCompanyId()) {
                                list.add(mBillList.get(i));
                            }
                        }
                        mAdapter.refreshData(list);
                    }
                    break;
                case RequestCodeKey.GO_PUBLISH_ACCEPTANCE:
                    boolean success = data.getBooleanExtra(IntentKey.SUCCESS, false);
                    if (success) {
                        getMyAcceptance();
                    }
                    break;
            }
        }
        super.

                onActivityResult(requestCode, resultCode, data);
    }

    private class MyOnSwipeMenuItemClickListener implements OnSwipeMenuItemClickListener {

        @Override
        public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition,
                                @DirectionMode int direction) {
            closeable.smoothCloseMenu();// 关闭被点击的菜单。
            switch (direction) {
                case Direction.RIGHT:
                    if (menuPosition == 0) {
                        mCurrentPosition = adapterPosition;
                        showDeleteAlert();
                    }
                    break;
            }
        }
    }

    private class MyOnItemClickListener implements OnItemClickListener {

        @Override
        public void onItemClick(RecyclerHolder holder, View view, int position) {
            XLog.e("当前item的位置" + position);
        }

    }

    private void showDeleteAlert() {
        AlertView alertView = new AlertView(this, null, "确定删除此单吗？", getString(R.string.cancel),
                new String[]{getString(R.string.confirm)}, null,
                AlertView.Style.Alert, new OnAlertItemClickListener() {
            @Override
            public void onItemClick(AlertView alertView, int position) {
                switch (position) {
                    case 0:
                        deleteMyAcceptance();
                        break;
                }
            }
        });
        alertView.show();
    }

}
